import { getUserLogin } from '../api.js';

export default {
    data() {
        return {
            username: '',
            user_id: '',
            password: '',
            error: '',
            token: localStorage.getItem('token') // 初始化 token
        };
    },

    computed: {
        isLoggedIn() {
            //return !!localStorage.getItem('token'); // 检查用户是否已登录
            return !!this.token; // 依赖 Vue 的响应式属性
        }
    },

    methods: {
        async login() {
            try {
                const response = await fetch(getUserLogin(), {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: this.username,
                        password: this.password
                    })
                });

                if (!response.ok) {
                    throw new Error('登录失败：用户名或密码错误');
                }

                alert("登录成功")
                console.log("login successfully!")
                
                const data = await response.json();
                this.token = data.access_token; // 更新 token
                localStorage.setItem('token', this.token); // 同步到 localStorage

                localStorage.setItem('user_id', data.user_id); // 存储 uid
                this.user_id = data.user_id;

                localStorage.setItem('username', data.username); // 存储 username
                // 登录成功后的操作，例如重定向
                this.$router.push('/'); // 登录成功后重定向到主页

            } catch (error) {
                this.error = error.message;
            }
        },
        logout() {
            localStorage.removeItem('token');
            localStorage.removeItem('uer_id');
            this.userId = '';
            localStorage.removeItem('username'); // 清除用户名

            this.$router.push('/login'); // 重定向到登录页面

            location.reload(); // 强制刷新页面
        },
    },

    created() {
        // 加载用户名
        this.username = localStorage.getItem('username') || '';
        this.user_id = localStorage.getItem('user_id') || '';
    },

    template:`
    <div class="container">
        <h2 v-if="isLoggedIn">login user: {{ username }}(uid: {{user_id}})</h2>
        <form v-else @submit.prevent="login">
            <h2>Login</h2>
            <div>
                <label for="username">Username:</label>
                <input type="text" v-model="username" required />
            </div>
            <div>
                <label for="password">Password:</label>
                <input type="password" v-model="password" required />
            </div>
            <button type="submit">Login</button>
            <p v-if="error">{{ error }}</p>
        </form>
        <button v-if="isLoggedIn" @click="logout">退出</button>
    </div>
    `
};